﻿#include "ssOpenGLSupport.h"
#include <cstdio>
#include "../3dMath/ss3dMathFunction.h"
#include "console/ssConsole.h"


namespace StarSeeker
{

#ifdef SS_USE_X11
	static int snglBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 16, None};
	static int dblBuf[]  = {GLX_RGBA, GLX_DEPTH_SIZE, 16, GLX_DOUBLEBUFFER, None};
#endif

int CheckGlError(const char* op)
{
	GLint error = glGetError();
	if (error)
	{
		if (op)
		{
#if defined(SS_USE_GLES2) || defined(SS_USE_ANDROID)
			SS_CONSOLE->Printf("after %s glError(0x%x)\n", op, error);
#else
			SS_CONSOLE->Printf("after %s glError(0x%x)：%s\n", op, error, gluErrorString(error));
#endif
		}
	}
	return error;
}

ssOpenGLSupport::ssOpenGLSupport()
{
	m_glDevice = 0;
	m_nWidth = 0;
	m_nHeight = 0;
}

ssOpenGLSupport::~ssOpenGLSupport()
{
	if (m_glDevice)
	{
		m_glDevice->CloseDevice();
		delete m_glDevice;
	}
}

bool ssOpenGLSupport::InitGLDevice(HWND hwnd, HDISPLAY hdis, int width, int height)
{
	if (!m_glDevice)
	{
		m_glDevice = CreateGLDevice();
		if (m_glDevice)
		{
			if (!m_glDevice->InitGLDevice(hdis, hwnd))
				return false;
			if (!m_glDevice->ChooseConfig())
				return false;
			if (!m_glDevice->CreateDevice())
				return false;
			if (!m_glDevice->SetCurrent())
				return false;
		}
	}
	m_nWidth = width;
	m_nHeight = height;

	m_check.GetOpenglInfo();
	return m_check.CheckGLSupport();
}

void ssOpenGLSupport::InitGLState(bool isWireFrame)
{
#if !defined(SS_USE_GLES2) && !defined(SS_USE_ANDROID)
	if (isWireFrame)
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}
	glColor3f(1, 1, 1);
	glDrawBuffer(GL_BACK);
	//glMatrixMode(GL_PROJECTION);
	//glLoadIdentity();
	//glMatrixMode(GL_MODELVIEW);
	//glLoadIdentity();
#endif
	glClearColor(0.5,0.5,0.5,1);
	glLineWidth(1.0);
	glViewport(0, 0, m_nWidth, m_nHeight);
	glEnable(GL_DEPTH_TEST);
	//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	//glEnable(GL_BLEND);
}

void ssOpenGLSupport::BeginRender()
{
	//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	//glEnableClientState(GL_VERTEX_ARRAY);
	//glPushMatrix();
}

void ssOpenGLSupport::EndRender()
{
	//glPopMatrix();
}

void ssOpenGLSupport::SetCullMode( int m )
{
	switch(m)
	{
	case SS_CULL_NULL:
		glDisable(GL_CULL_FACE);
		return;
	case SS_CULL_CW:
		glFrontFace(GL_CW);
		glEnable(GL_CULL_FACE);
		return;
	case SS_CULL_CCW:
		glFrontFace(GL_CCW);
		glEnable(GL_CULL_FACE);
		return;
	default:
		return;
	}
}

}
